<template>
	<el-dialog width="500px" :show-close="false" v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false">
		<div class="cc-flex flex-h-center">
			<div style="width: 500px">
				<el-form label-position="top" ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px">
					<el-form-item prop="question" label="问题标题">
						<el-input v-model="dataForm.question"></el-input>
					</el-form-item>
					<el-form-item prop="answer" label="回答">
						<el-input v-model="dataForm.answer" :autosize="{ minRows: 2, maxRows: 10 }" type="textarea" placeholder="Please input" />
					</el-form-item>
				</el-form>
			</div>
		</div>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { MQuestion, ConfigService } from '@/modules/system'
import type { FormInstance, FormRules } from 'element-plus'

const emit = defineEmits<{
	(e: 'refreshDataList', value?: string | undefined): void
}>()

const visible = ref(false)
const dataFormRef = ref<FormInstance>()
const dataForm: MQuestion = reactive({
	question: '',
	answer: ''
})

const dataRules = reactive<FormRules>({
	question: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
	answer: [{ required: true, message: '请输入答案', trigger: ['blur', 'change'] }]
})

async function init(data?: MQuestion) {
	visible.value = true
	// 重置表单数据
	dataForm.id = ''
	await dataFormRef.value?.resetFields()
	if (data) Object.assign(dataForm, data)
}

// 表单提交
function submitHandle() {
	dataFormRef.value?.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		ConfigService.editQuestion(dataForm)
			.then(() => {
				visible.value = false
				emit('refreshDataList')
				ElMessage.success({
					message: '保存成功'
				})
			})
			.catch(() => {
				visible.value = false
				ElMessage.error({
					message: '保存异常'
				})
			})
	})
}

defineExpose({
	init
})
</script>
<style scope lang="scss">
</style>
